package com.dmx.cep.action.contentManage;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.net.ftp.FTPFile;

import com.dmx.fw.exception.GeneralException;
import com.dmx.fw.exception.GeneralExceptionHandler;
import com.dmx.fw.web.struts2.action.BaseAction;

import com.dmx.adi.ADIException;
import com.dmx.adi.ADIFormatException;
import com.dmx.adi.AdiParseUtil;
import com.dmx.adi.AdiRemotePackageValidator;
import com.dmx.adi.AssetStatusUpdateException;
import com.dmx.adi.PosterNotFoundException;
import com.dmx.adi.VideoNotFoundException;
import com.dmx.cep.entity.AdiImportTask;
import com.dmx.cep.entity.FtpServerConfig;
import com.dmx.cep.entity.VodContentInfo;
import com.dmx.cep.service.ContentService;
import com.dmx.net.ConnectionException;
import com.dmx.net.HostInfoExtractor;
import com.dmx.net.ftp.impl.FtpClient;
import com.dmx.net.ftp.impl.RemoteFtpFileNotExistsException;

public class AssetImportAction extends BaseAction{
	
	private String msgError = "";
	
	private String taskName;
	
	private String ftpUrl;
	
	private ContentService contentService;
	
	private String siteId;
	
	public final static String adiFileName = "adi.xml";
	
	private List<String> ftpFilePathList=new ArrayList<String>(0);
	
	public String getTaskName() {
		return taskName;
	}

	public void setTaskName(String taskName) {
		this.taskName = taskName;
	}

	//进入ADI导入界面
	public String doImportInput(){
		
		if(ftpUrl==null){
			FtpServerConfig ftpServerConfig = contentService.getFtpServer(1);
			StringBuffer sb = new StringBuffer();
			if (ftpServerConfig != null) {
				sb.append("ftp://");
				sb.append(ftpServerConfig.getUserName());
				sb.append(":");
				sb.append(ftpServerConfig.getUserPW());
				sb.append("@");
				sb.append(ftpServerConfig.getServerIP());
				sb.append(":");
				sb.append(ftpServerConfig.getServerPort());
				sb.append("/");
				sb.append(ftpServerConfig.getFileDir());
				sb.append("/adi.xml");
				ftpUrl = sb.toString();
			}
		}
		return "adiImport";
	}
	
	//进入ADI批量导入界面
	public String doBatchImportInput(){
		if (ftpUrl == null) {
			FtpServerConfig ftpServerConfig = contentService.getFtpServer(1);
			StringBuffer sb = new StringBuffer();
			if (ftpServerConfig != null) {
				sb.append("ftp://");
				sb.append(ftpServerConfig.getUserName());
				sb.append(":");
				sb.append(ftpServerConfig.getUserPW());
				sb.append("@");
				sb.append(ftpServerConfig.getServerIP());
				sb.append(":");
				sb.append(ftpServerConfig.getServerPort());
				sb.append("/");
				sb.append(ftpServerConfig.getFileDir());

				ftpUrl = sb.toString();
			}
		}
		return "adiBatchImport";
	}	
	
	public String doImport() throws Exception{
		log.info("ftpUrl= "+ftpUrl);
		try{
			ftpUrl=ftpUrl.trim();
			if (!testFtpFileExists()) {
				this.setErrorInfo(msgError);
				return doImportInput();
			} else {
				VodContentInfo contentInfo=new VodContentInfo();
				try{
					AdiParseUtil.adiValidation(contentInfo,ftpUrl,contentService);
				}catch(ADIException ae){
					this.setErrorInfo(getText("adi.parse.exception"));
					return doImportInput();
				}catch(ADIFormatException afe){
					this.setErrorInfo(getText("adi.format.exception"));
					return doImportInput();
				}catch(AssetStatusUpdateException aue){
					this.setErrorInfo(getText("asset.update.error"));
					return doImportInput();
				}catch(VideoNotFoundException ve){
					this.setErrorInfo(getText("video.not.found.exception"));
					return doImportInput();
				}catch(PosterNotFoundException ve){
					this.setErrorInfo(getText("poster.not.found.exception"));
					return doImportInput();
				}catch(Exception e){
					this.setErrorInfo(getText(e.getMessage()));
					return doImportInput();
				}
				
				AdiImportTask task = new AdiImportTask();
				task.setTaskName(taskName+" : "+contentInfo.getTitle());
				task.setAssetId(contentInfo.getContid());
				task.setFtpUrl(ftpUrl);
				task.setCreationTime(new Date());
				task.setSiteId(siteId);
				contentService.saveObject(task);
				this.setSuccessinfo(this.getText("adi.import.success"));
			}
		}catch(Exception e){
			GeneralException ge = GeneralExceptionHandler.Handle(e);
			this.setErrorInfo(this.getText(ge.getMessage()));
		}
		return doImportInput();
	}
	
	public String doBatchImport(){
		try{
			ftpUrl=ftpUrl.trim();
			if (!testFtpFolderExists()) {
				this.setErrorInfo(msgError);
			} else {
				for(int i=0;i<ftpFilePathList.size();i++){
					String _ftpUrl=ftpFilePathList.get(i);
					
					VodContentInfo contentInfo=new VodContentInfo();
					try{
						AdiParseUtil.adiValidation2(contentInfo,_ftpUrl);
					}catch(Exception e){
						log.error(e);
					}
					
					AdiImportTask task = new AdiImportTask();
					task.setTaskName(taskName+"("+i+") : "+contentInfo.getTitle());
					task.setAssetId(contentInfo.getContid());

					task.setFtpUrl(_ftpUrl);
					task.setCreationTime(new Date());
					task.setSiteId(siteId);
					contentService.saveObject(task);
				}
				
				this.setSuccessinfo(this.getText("adi.import.success"));
			}
		}catch(Exception e){
			GeneralException ge = GeneralExceptionHandler.Handle(e);
			this.setErrorInfo(this.getText(ge.getMessage()));
		}
		return doBatchImportInput();
	}
	
	private boolean testFtpFileExists() throws Exception {
		FtpClient ftpClient = new FtpClient();
		try {
			URL url = null;
			try {
				url = new URL(ftpUrl);
			} catch (MalformedURLException exception) {
				msgError = getText("urlError");
				log.error(exception);
				return false;
			}

			HostInfoExtractor hostInfoExtractor = new HostInfoExtractor(url);

			hostInfoExtractor.decorateNetworkProtocolClient(ftpClient);

			try {
				ftpClient.doLogin();
			} catch (Exception e) {

			}

			if (ftpClient.isLogined() == false) {
				msgError=getText("loginError");
				return false;
			}

			if (ftpClient.cdToRemoteDir(hostInfoExtractor.extractTheFolder()) == false) {
				msgError=getText("cdToFolderError");
				return false;
			}
			
			ftpClient.testRemoteFileExists(hostInfoExtractor.extractFileName());


		} catch (ConnectionException ce) {
			this.setMsgError(getText("networkError"));
			return false;

		}  catch(RemoteFtpFileNotExistsException rfe){
			StringBuffer strBuf = new StringBuffer(); 
			strBuf.append(getText("fileNotExistsError"));
			this.setMsgError(strBuf.toString());
			return false;
		}
		finally {
			try {
				ftpClient.close();
			} catch (Exception e) {

			}
		}
		return true;
	}
	
	private boolean testFtpFolderExists() throws Exception {
		if(!ftpUrl.endsWith("/")){
			ftpUrl+="/";
		}
		FtpClient ftpClient = new FtpClient();
		try {
			URL url = null;
			try {
				url = new URL(ftpUrl);
			} catch (MalformedURLException exception) {
				msgError = getText("urlError");
				return false;
			}

			HostInfoExtractor hostInfoExtractor = new HostInfoExtractor(url);

			hostInfoExtractor.decorateNetworkProtocolClient(ftpClient);

			try {
				ftpClient.doLogin();
			} catch (Exception e) {

			}

			if (ftpClient.isLogined() == false) {
				this.setMsgError(getText("loginError"));
				return false;
			}
			
			String remoteDir = hostInfoExtractor.extractTheFolder();

			if (ftpClient.cdToRemoteDir(remoteDir) == false) {
				this.setMsgError(getText("cdToFolderError"));
				return false;
			}
			
			if (remoteDir.endsWith("/") == false) {
				remoteDir += "/";
			}
			
			FTPFile[] remoteFiles = ftpClient.listFiles();
			
			for (FTPFile f : remoteFiles) {
				if (f.isDirectory() == true
						&& f.getName().endsWith(".") == false
						&& f.getName().endsWith("..") == false) {
					String remoteAdiFolder = remoteDir + f.getName();
					ftpClient.cdToRemoteDir(remoteAdiFolder);
					FTPFile remoteFilesInDir[] = ftpClient.listFiles();
					
					for (FTPFile _f : remoteFilesInDir) {
						if (_f.getName().equalsIgnoreCase(adiFileName)) {
							ftpFilePathList.add(ftpClient.getCurrentWorkingDirectoryFullUrl()+_f.getName());
							break;
						}
					}
				}
			}
			
			if(ftpFilePathList.size()==0){
				this.setMsgError(getText("no.adi.files.import"));
				return false;
			}

			return true;
		} finally {
			try {
				ftpClient.close();
			} catch (Exception e) {

			}
		}
	}
	


	public String getFtpUrl() {
		return ftpUrl;
	}

	public void setFtpUrl(String ftpUrl) {
		this.ftpUrl = ftpUrl;
	}

	public String getMsgError() {
		return msgError;
	}

	public void setMsgError(String msgError) {
		this.msgError = msgError;
	}

	public ContentService getContentService() {
		return contentService;
	}

	public void setContentService(ContentService contentService) {
		this.contentService = contentService;
	}

	public String getSiteId() {
		return siteId;
	}

	public void setSiteId(String siteId) {
		this.siteId = siteId;
	}	
}
